// TODO 把这里涉及pinia的移动到pinia中
import router from '@/router';
import piniaStore from '@/store';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { constantRoutes } from '@/router';
import { getRouters } from '@/api/menu';
import { getToken } from '@/utils/auth';
import { usePermissionStore, useUserStore } from '@/store';

NProgress.configure({ showSpinner: false });
const modules = import.meta.glob('../views/*/*.vue');
/** 在免登录白名单，直接进入 */
const whiteList = [
  '/login',
  //   "/loginAuthentication",
  //   "/loginHide",
  //   "/auth-redirect",
  //   "/bind",
  //   "/register",
];
const permissionStore = usePermissionStore(piniaStore);
const userStore = useUserStore(piniaStore);
const generateRoutes = () => {
  return new Promise((resolve) => {
    // 向后端请求路由数据
    getRouters().then((res) => {
      /** */
      // console.log(res);
      const result = res.data;
      const sdata = JSON.parse(JSON.stringify(result));
      const rdata = JSON.parse(JSON.stringify(result));
      const sidebarRoutes = filterAsyncRouter(sdata);
      const rewriteRoutes = filterAsyncRouter(rdata, true);
      rewriteRoutes.push({ path: '/:pathMatch(.*)', redirect: 'home', hidden: true });
      // commit("SET_ROUTES", rewriteRoutes);
      // commit("SET_SIDEBAR_ROUTERS", constantRoutes.concat(sidebarRoutes));
      // commit("SET_DEFAULT_ROUTES", sidebarRoutes);
      // commit("SET_TOPBAR_ROUTES", sidebarRoutes);
      permissionStore.setRoutes(rewriteRoutes);
      permissionStore.setSidebarRoutes(constantRoutes.concat(sidebarRoutes));
      permissionStore.setDefaultRoutes(sidebarRoutes);
      permissionStore.setTopbarRoutes(sidebarRoutes);
      resolve(rewriteRoutes);
    });
  });
};

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap, type = false) {
  return asyncRouterMap.map((route) => {
    const newRoute = { ...route };
    if (type && route.children) {
      newRoute.children = filterChildren(route.children);
    }
    if (route.component) {
      // Layout ParentView 组件特殊处理
      // if (route.component === "Layout") {
      //   route.component = Layout;
      // } else if (route.component === "ParentView") {
      //   route.component = ParentView;
      // } else if (route.component === "InnerLink") {
      //   route.component = InnerLink;
      // } else {
      newRoute.component = loadView(route.component);
      // }
    }
    if (route.children != null && route.children && route.children.length) {
      newRoute.children = filterAsyncRouter(route.children, type);
    } else {
      delete newRoute['children'];
      delete newRoute['redirect'];
    }
    return newRoute;
  });
}

function filterChildren(childrenMap, lastRouter?) {
  let children: any[] = [];
  childrenMap.forEach((el) => {
    if (el.children && el.children.length) {
      if (el.component === 'ParentView') {
        el.children.forEach((c) => {
          c.path = el.path + '/' + c.path;
          if (c.children && c.children.length) {
            children = children.concat(filterChildren(c.children, c));
            return;
          }
          children.push(c);
        });
        return;
      }
    }
    if (lastRouter?.path) {
      el.path = lastRouter.path + '/' + el.path;
    }
    children = children.concat(el);
  });
  return children;
}

function dynamicRouter(routers: any[]) {
  const list: any[] = [];
  routers.forEach((itemRouter, index) => {
    list.push({
      ...itemRouter,
      components: modules[`../views${itemRouter.component}`],
    });
    if (itemRouter.children?.length) {
      list[index].children = dynamicRouter(itemRouter.children);
    }
  });
  return list;
}

export const loadView = (view) => {
  // 路由懒加载
  return () => require(`@/views/${view}`);
};

// 防止首次或者刷新界面路由失效
let registerRouteFresh = true;
router.beforeEach((to, _from, next) => {
  NProgress.start();
  userStore.switchPage();
  const token = getToken();
  if (token && token != 'undefined') {
    // to.meta.title && store.dispatch('settings/setTitle', to.meta.title);
    /* has token*/
    if (to.path === '/login') {
      next({ path: '/' });
      NProgress.done();
    } else {
      if (userStore.roles.length === 0) {
        // 判断当前用户是否已拉取完user_info信息
        userStore
          .GetInfo()
          .then(() => {
            generateRoutes().then((accessRoutes: any[] = []) => {
              // 根据roles权限生成可访问的路由表
              if (registerRouteFresh) {
                dynamicRouter(accessRoutes).forEach((itemRouter) => {
                  router.addRoute(itemRouter);
                });
                next({ ...to, replace: true });
                registerRouteFresh = false;
              } else {
                next();
              }
              //   router.addRoutes(accessRoutes); // 动态添加可访问路由表
              //   next({ ...to, replace: true }); // hack方法 确保addRoutes已完成
            });
          })
          .catch((_err) => {
            userStore.Logout();
            // .then(() => {
            //   Message.error(err)
            //   next({ path: '/' })
            // })
          });
      } else {
        next();
      }
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      /** 在免登录白名单，直接进入 */
      next();
    } else {
      next(`/login`); // 否则全部重定向到登录页
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});
